<script lang="ts" setup>
  import { defineProps, ref, watch, defineEmits,nextTick } from "vue"
  import gmDialog from '@/components/Dialog/index.vue'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { cloneDeep } from "lodash-es"
  import iconSelect from '@/components/IconSelect/index.vue'
  import { type FormInstance, type FormRules, ElMessage } from "element-plus"
  import useFile from '@/hooks/useFile'

  interface Props {
    data?: any,
  }

  const props = withDefaults(defineProps<Props>(), {
    data: ()=>({}),
  })
  const { beforeUpload,beforeAvatarUpload, uploadUrl, uploadImage } = useFile({ maxSize: 10, fileType: 'image' })
  const form = ref<any>(cloneDeep(props.data) || {})
  const formRef = ref<FormInstance>()
  const dialogRef = ref<InstanceType<typeof gmDialog>>()
  const emit = defineEmits(['cancel','success'])

  let fileUploadBtn =ref<any>()

  const fileArr = ref([])

  const rules: FormRules = {
    name: [
      { required: true, message: '请输入合同名称', trigger: 'change' },
    ],
    startTime: [
      { required: true, message: '请选择合同开始时间', trigger: 'change' },
    ],
    endTime: [
      { required: true, message: '请选择合同结束时间', trigger: 'change' },
    ],
    requestPayNum: [
      { required: true, message: '请选择合同内请款次数', trigger: 'change' },
    ],
  }

  const cancel = ()=>{
    emit('cancel')
  }

  const success =  async(formEl: FormInstance | undefined)=>{
    await formEl?.validate((valid) => {
      if (!valid) {
        return
      }
      console.log(form.value,'form.value')

      emit('success', form.value)
    })
  }

  const handleUploadSuccess1 = (res: any, file: any) => {
    console.log(res,'resresres')
    ElMessage({
      message: '上传成功',
      type: 'success',
    });
    form.value.attachment = []
    form.value.attachment.push(res.result)
    // Get the contract name from the response and assign it to form.name without the file extension
    form.value.name = file.name.replace(/\.[^/.]+$/, ""); // Remove the file extension
    nextTick(() => {
      // 清空上传组件的文件列表
      if (fileUploadBtn.value) {
        fileUploadBtn.value.clearFiles();
        // 重置 input 的值，确保下次选择相同文件也能触发
        const input = fileUploadBtn.value.$el.querySelector('input[type="file"]') as HTMLInputElement;
        if (input) {
          input.value = '';
        }
      }
    });
  }

  const handleUploadDel = (src: string) => {
    console.log(src, 'sev', form.value.attachment)
    form.value.attachment = form.value.attachment.filter((i) => i !== src)
  }
  
  const imgPreview = (file: any) => {
    console.log(file,'filefilefile')
    fileArr.value = [];
    fileArr.value.push(file);
    form.value.position = "";
    console.log(file);
    form.value.position = file.name;
    let fileName = file.name;
    let regex = /(.jpg|.jpeg|.gif|.png|.pdf)$/;
    if (regex.test(fileName.toLowerCase())) {
      console.log(URL.createObjectURL(file.raw),1111);
    } else {
      ElMessage.error("请选择图片文件");
    }
  }

  const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
  }
  
  const handleDownload = (attachmentUrl: string) => {
    if (attachmentUrl) {
      window.open(attachmentUrl, '_blank'); 
    } else {
      ElMessage({
        message: '没有可用的附件',
        type: 'warning',
      });
    }
  };
</script>

<template>
  <gm-dialog
    ref="dialogRef"
    title="添加/编辑合同"
    :width="800"
    @cancel="cancel"
    @comfirm="success(formRef)">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- <el-form-item label="附件" prop="attachment">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
              <el-icon class="upload-img-action"><Plus /></el-icon>
            </el-upload>
            <div class="form-value-flex" v-if="form.attachment&&form.attachment.length>0">
              <uploadImage v-for="item in form.attachment" :src="item" @del="handleUploadDel(item)" class="upload-img-image" />
            </div>
          </el-form-item>-->
          <el-form-item label="合同附件pdf" prop="attachment"> 
            <el-upload
              ref="fileUploadBtn"
              class="avatar-uploader"
              :action="uploadUrl"
              :file-list="fileArr"
              :on-change="imgPreview"
              :on-preview="handlePreview"
              :limit="1"
              :show-file-list="false"
              :on-success="handleUploadSuccess1"
              :before-upload="beforeAvatarUpload"
              accept=".pdf">
              <el-icon class="upload-img-action"><Plus /></el-icon>
            </el-upload>
            <div v-if="form.attachment&&form.attachment.length>0">
              <!-- <div v-for="(item,index) in form.attachment" :key="index">
                {{item}}
              </div> -->
              <div v-for="(item,index) in form.attachment" :key="index" class="pdfstyle" @click="handleDownload(item)">
                {{form.name}}
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  prop="name" label="合同名称">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item  prop="startTime" label="合同开始时间">
            <el-date-picker v-model="form.startTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" style="width:100%;" placeholder="请选择"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  prop="endTime" label="合同结束时间">
            <el-date-picker v-model="form.endTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" style="width:100%;" placeholder="请选择"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item  prop="requestPayNum" label="合同内请款次数">
            <el-input v-model="form.requestPayNum" type="number" placeholder="请输入">
              <template #append>次</template>
            </el-input>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
  </gm-dialog>
</template>


<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  .el-icon{
    color:#333;
    font-size:20px;
  }
}
.pdfstyle{
  color:#D68E44;
  text-decoration:underline;
  cursor: pointer;
}
</style>
